package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;

/**
 * @package com.heima.admin.service.impl
 * @Date 2022/2/26
 * @project heima-leadnews
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO adu) {
        if (StringUtils.isBlank(adu.getName())||StringUtils.isBlank(adu.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户名或密码不能为空");
        }
        AdUser aduser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adu.getName()));
        if (aduser==null){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        if (aduser.getStatus()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        String salt = aduser.getSalt();
        String newPassword = DigestUtils.md5DigestAsHex((adu.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
        if (!newPassword.equals(aduser.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        aduser.setLoginTime(new Date());
        updateById(aduser);
        //生成token
        String token = AppJwtUtil.getToken(aduser.getId().longValue());
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(aduser,adUserVO);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
